package cn.edu.hpu.jie.dao;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

import cn.edu.hpu.jie.entity.News;
import cn.edu.hpu.jie.entity.NewsSites;
import cn.edu.hpu.jie.util.RowMapping;
import cn.edu.hpu.jie.util.VoteDB;

public class NewsDao {
	private VoteDB<News> nDB = new VoteDB<News>();
	private VoteDB<NewsSites> nsDB = new VoteDB<NewsSites>();
	
	private class NewsMapping implements RowMapping<News>{

		public News getMapping(ResultSet rs) throws SQLException {
			News n = new News();
			n.setId(rs.getInt("id"));
			n.setCreatetime(rs.getString("createtime"));
			n.setNum(rs.getInt("num"));
			n.setTitle(rs.getString("title"));
			n.setWriter(rs.getString("writer"));
			return n;
		}
	}
	
	private class NewsSitesMapping implements RowMapping<NewsSites>{

		public NewsSites getMapping(ResultSet rs) throws SQLException {
			NewsSites ns = new NewsSites();
			ns.setContent(rs.getString("content"));
			ns.setCreatetime(rs.getString("createtime"));
			ns.setId(rs.getInt("id"));
			ns.setNum(rs.getInt("num"));
			ns.setSubtitle(rs.getString("subtitle"));
			ns.setTitle(rs.getString("title"));
			ns.setWriter(rs.getString("writer"));
			return ns;
		}
	}
	
	public int insertNews(NewsSites n) {
		String sql = "INSERT INTO t_news(title, writer, createtime, num) VALUES (?, ?, ?, ?)";
		int id = nDB.getInsertPrimaryKey(sql, n.getTitle(), n.getWriter(), n.getCreatetime(), n.getNum());
		String nsql = "INSERT INTO t_news_sites (id, subtitle, content) VALUES (?, ?, ?)";
		nsDB.updateData(nsql, id, n.getSubtitle(), n.getContent());
		return id;
	}
	
	public List<News> getAllNews() {
		String sql = "SELECT id, createtime, writer, num, title FROM t_news";
		return nDB.getAll(sql, new NewsMapping());
	}

	public NewsSites getNewsSitesById(int id) {
		String sql = "SELECT a.id AS id, createtime, writer, num, title, subtitle, content FROM t_news as a, t_news_sites AS b WHERE a.id = ? AND a.id = b.id";
		return nsDB.getObject(sql, new NewsSitesMapping(), id);
	}

	public void editNewsById(NewsSites ns) {
		String sql = "UPDATE t_news SET title = ?, writer = ? WHERE id = ?";
		nDB.updateData(sql, ns.getTitle(), ns.getWriter(), ns.getId());
		String ssql = "UPDATE t_news_sites SET subtitle = ?, content = ? WHERE id = ?";
		nsDB.updateData(ssql, ns.getSubtitle(), ns.getContent(), ns.getId());
	}
}
